#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
诊断企业微信agent配置问题
"""

import os
import requests
from config.settings import settings

def diagnose_config():
    """诊断配置问题"""
    print("🔍 诊断企业微信配置问题...")
    print("=" * 50)
    
    print("📋 当前配置:")
    print(f"   WX_CORPID: {settings.WX_CORPID}")
    print(f"   WX_CORPSECRET: {settings.WX_CORPSECRET[:10]}***")
    print(f"   WX_AGENT_ID: {settings.WX_AGENT_ID}")
    print(f"   WX_AGENT_SECRET: {settings.WX_AGENT_SECRET[:10]}***")
    
    # 检查配置是否相同
    if settings.WX_CORPSECRET == settings.WX_AGENT_SECRET:
        print("\n⚠️  问题发现: WX_CORPSECRET 和 WX_AGENT_SECRET 相同!")
        print("   这可能导致权限问题，因为:")
        print("   - WX_CORPSECRET 应该用于获取企业access_token（用于企业内部消息）")
        print("   - WX_AGENT_SECRET 应该用于获取客服access_token（用于客服操作）")
    
    print("\n🔑 测试access_token获取...")
    
    # 测试企业应用access_token
    corp_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    corp_params = {
        'corpid': settings.WX_CORPID,
        'corpsecret': settings.WX_CORPSECRET
    }
    
    try:
        corp_resp = requests.get(corp_url, params=corp_params, timeout=10)
        corp_json = corp_resp.json()
        
        if corp_json.get("errcode") == 0:
            corp_token = corp_json.get("access_token")
            print(f"✅ 企业应用access_token获取成功")
            
            # 测试企业内部消息发送
            test_internal_message(corp_token, settings.WX_AGENT_ID)
        else:
            print(f"❌ 企业应用access_token获取失败: {corp_json}")
    except Exception as e:
        print(f"❌ 企业应用access_token获取异常: {str(e)}")
    
    # 测试客服应用access_token
    agent_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    agent_params = {
        'corpid': settings.WX_CORPID,
        'corpsecret': settings.WX_AGENT_SECRET
    }
    
    try:
        agent_resp = requests.get(agent_url, params=agent_params, timeout=10)
        agent_json = agent_resp.json()
        
        if agent_json.get("errcode") == 0:
            agent_token = agent_json.get("access_token")
            print(f"✅ 客服应用access_token获取成功")
        else:
            print(f"❌ 客服应用access_token获取失败: {agent_json}")
    except Exception as e:
        print(f"❌ 客服应用access_token获取异常: {str(e)}")

def test_internal_message(access_token, agent_id):
    """测试发送企业内部消息"""
    print(f"\n🔍 测试发送企业内部消息...")
    
    url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
    
    payload = {
        "touser": "LiXingChen",
        "msgtype": "text",
        "agentid": agent_id,
        "text": {
            "content": "🔔 测试企业内部消息发送"
        }
    }
    
    try:
        resp = requests.post(url, json=payload, timeout=10)
        resp_json = resp.json()
        
        print(f"📡 HTTP响应状态码: {resp.status_code}")
        print(f"📡 HTTP响应内容: {resp_json}")
        
        if resp_json.get("errcode") == 0:
            print(f"✅ 企业内部消息发送成功")
        elif resp_json.get("errcode") == 301002:
            print(f"❌ 权限错误: 当前access_token无权操作agentid {agent_id}")
            print(f"   建议: 检查WX_AGENT_SECRET配置是否正确")
        else:
            print(f"❌ 企业内部消息发送失败: {resp_json}")
    except Exception as e:
        print(f"❌ 企业内部消息发送异常: {str(e)}")

def suggest_fix():
    """提供修复建议"""
    print("\n" + "=" * 50)
    print("💡 修复建议:")
    print("1. 检查企业微信管理后台的应用配置")
    print("2. 确保WX_CORPSECRET是企业应用的Secret")
    print("3. 确保WX_AGENT_SECRET是客服应用的Secret")
    print("4. 如果只有一个应用，可以暂时使用相同的Secret")
    print("5. 或者修改代码，只使用一个access_token")

if __name__ == "__main__":
    diagnose_config()
    suggest_fix() 